﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using YawetagLib.Linq;

namespace YawetagLib.Data.Xml
{
    public class DataContext : IQueryableDataContext
    {
        public DataContext(string filePath)
        {
            Connection = new Connection(filePath);

            DataSets = new Dictionary<Type, IQueryable>();
            References = new Dictionary<string, object>();
        }

        public void OpenConnection()
        {
            Connection.Open();
        }

        public void CloseConnection()
        {
            Connection.Close();
        }

        public IDataSource<TEntity> GetDataSource<TEntity>() where TEntity : class
        {
            return new DataSource<TEntity>(this);
        }

        public void SubmitChanges()
        {
            Connection.Submit();
        }

        public IQueryable<TEntity> GetDataSet<TEntity>() where TEntity : class
        {
            if (!DataSets.ContainsKey(typeof(TEntity)))
            {
                DataSets.Add(typeof(TEntity), new Query<TEntity>(GetQueryProvider<TEntity>()));
            }

            return (IQueryable<TEntity>)DataSets[typeof(TEntity)];
        }

// ReSharper disable UnusedTypeParameter
        private static IQueryProvider GetQueryProvider<TEntity>() where TEntity : class
// ReSharper restore UnusedTypeParameter
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            Connection.Dispose();
        }

        public object Current
        {
            get { return this; }
        }

        public XDocument Document
        {
            get { return Connection.GetDocument(); }
        }

        private Connection Connection { get; set; }

        private IDictionary<Type, IQueryable> DataSets { get; set; }

        internal IDictionary<string, object> References { get; set; }
    }
}
